<?php

// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2020 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\index\controller;

use app\index\BaseController;
use app\index\model\user\UserCard;
use app\index\model\user\WechatUser;
use app\service\jwt\IndexJwtService;
use app\service\sms\AliSms;
use app\service\weChat\WeChatAppletService;
use app\service\weChat\WeChatService;
use Exception;
use think\facade\Db;
use think\facade\Log;
use app\index\model\user\User;
use app\index\model\sms\SmsRecord;
use think\facade\Cache;
use think\facade\Request;
/**
 * Class Auth
 * @package app\controller\api
 * @author xaboy
 * @day 2020-05-06
 */
class Auth extends BaseController
{

    /**
     * 登录
     * @return $this
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function login(){
        $account = $this->request->param('account');
        $password = $this->request->param('password');
        if (!$account) return $this->fail('请输入账号');
        if (!$password) return $this->fail('请输入密码');
        $user = Db::table('jy_user')->where('account',$account)->find();
        if (!$user) return $this->fail('当前账户未注册，请注册');
        if($user['status'] == 0 ) return $this->fail('账号已被冻结');
        if (empty($user['log_pwd'])) return $this->fail('请重置密码');
        if (!password_verify($pwd = (string)$password, $user['log_pwd'])){
            return $this->fail('账户或者密码错误');
        }
        $exp = intval(config('index.user_token_valid_exp', 15));
        $jwtTokenService = new IndexJwtService();
        $tokenInfo = $jwtTokenService->createToken($user,'user',strtotime("+ {$exp}day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
        ];
        $userResult = Db::table('jy_user')->where('id',$user['id'])->update($saveData);
        $backUser = [
            'user_id'=>$user['id'],
            'account'=>$user['account'],
            'real_name'=>$user['real_name'],
            'nickname'=>$user['nickname'],
            'phone'=>$user['phone'],
            'now_money'=>$user['now_money'],
        ];
        return $this->success('获取成功',compact('backUser','tokenInfo'));
    }

    /**
     * TODO 注册账号
     * @param UserAuthValidate $validate
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function register()
    {
        $data = request()->param(['account', 'sms_code', 'spread', 'pwd']);
        $data['phone'] = $data['account'];
        $data['user_type'] = 1;//1表示h5注册
        //Log::info('注册获取到的参数：'.json_encode($data,JSON_UNESCAPED_UNICODE));
        $userModel = new User();
        $smsRecordModel = new SmsRecord();
        //验证码判断
        $smsWhere = ['phone'=>$data['phone'],'type'=>'register'];
        $getInfo = $smsRecordModel->where($smsWhere)->order('sms_record_id','desc')->find();
        if(!$getInfo || (strtotime($getInfo['create_time']) + 30*60) < time() || $getInfo['is_use'] == 1){
            //return $this->fail('验证码已经过期');
        }
        //判断验证码是否正确
        if($getInfo['code'] != $data['sms_code']){
            //return $this->fail('验证码错误');
        }
        //判断手机号是否被注册
        $user = $userModel->where('account',$data['phone'])->find();
        if ($user){
            $smsRecordModel->where('sms_record_id',$getInfo['sms_record_id'])->update(['is_use'=>1]);
            return $this->fail('用户已存在');
        }
        //用户注册
        Db::startTrans();
        $incResult = true;
        $addResult = $userModel->registerUser($data);
        //修改短信为使用状态
        $smsRecordModel->where($smsWhere)->update(['is_use'=>1]);
        if($addResult && $incResult){
            Db::commit();
            return $this->success('注册成功');
        }else{
            return $this->fail('注册失败，请重新注册');
            Db::rollback();
        }
    }

    /**
     * 使用短信接口发短信
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function getSms(){
        $data = request()->param(['phone', 'type']);
        if(!$data['phone']) return $this->fail('请填写正确手机号');
        if(!$data['type']) return $this->fail('10002');
        //增加短信限制
        $smsRecordModel = new SmsRecord();
        $phoneWhere = [
            ['phone','=',$data['phone']],
            ['create_time','>=',(date("Y-m-d")." 00:00:00")],
            ['type','=',$data['type']],
            //['is_use','=',0],
        ];
        $getList = $smsRecordModel->where($phoneWhere)->order('create_time','desc')->select()->toArray();
        if(count($getList) >= 10){
            return $this->fail('当前号码当天短信发送数量达到上限');
        }
        if(!empty($getList) && (strtotime($getList[0]['create_time']) + 60) > time()){
            return $this->fail('短信发送过于频繁，请稍后重试');
        }
        $data['template'] = 'VERIFICATION_CODE';//短信模板
        $data['sign_name'] = 'VERIFICATION_CODE';//短信签名
        $sms_time = 5;
        $aliSms = new AliSms();
        Db::startTrans();
        $data['code'] =  $aliSms->getCode( 6);
        $data['content'] =  '【充电桩】您的验证码是：'.$data['code'].'，有效期为'.$sms_time.'分钟。如非本人操作，可不予理会。';
        $addSmsRecord = $smsRecordModel->addData($data);
        if($addSmsRecord){
            $getInfo = $aliSms->send($data);
            if($getInfo['status'] == 0){
                Db::commit();
                return $this->success('验证码发送成功');
            }else{
                Db::rollback();
                return $this->fail('验证码发送失败，请稍后重试',1,400,$getInfo);
            }
        }else{
            return $this->fail('验证码发送失败，请稍后重试');
        }
    }

    /**
     * 用户信息
     * @return $this
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function userInfo(){
        $userId = $this->request->uid();
        $userModel = new User();
        $userInfo = $userModel->getUserInfoById($userId);
        if($userInfo['status'] == 0){
            return $this->fail('用户被禁用，请联系客服');
        }

        $backUser = [
            'user_id'=>$userInfo['id'],
            'account'=>$userInfo['account'],
            'nickname'=>$userInfo['nickname'],
            'avatar'=>$userInfo['avatar'] ? $userInfo['avatar'] : config('add.web_url').config('add.userDefaultImg'),
            'now_money'=>$userInfo['now_money'],
            'sex'=>$userInfo['sex'],
            'real_name'=>$userInfo['real_name'],
            'red_money'=>0,
            'carbon_integral'=>0,
            'charge_money'=>1,
        ];
//        $userCardModel = new UserCard();
//        $userCardInfo = $userCardModel->getInfoByWhere(['user_id'=>$userInfo['id'],'is_delete'=>1]);
//        $backUser['user_card'] = $userCardInfo;
        return $this->success('获取用户信息成功',$backUser);
    }

    /**
     * @param UserRepository $repository
     * @return mixed
     * @author xaboy
     * @day 2020/6/1
     */
    public function logout()
    {
        $userModel = new User();
        $token = $this->request->header('X-Token');
        $userModel->clearToken($token);
        return $this->success('退出登录成功');
    }

    /**
     * 绑定用户
     * @param UserRepository $userRepository
     * @return $this
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function bindUserRecord(){
        $data =  Request::post();
        if(!$data['phone']) return $this->fail('请输入手机号');
        if(!$data['sms_code']) return $this->fail('请输入验证码');
        //if(!$data['spread']) return $this->fail('请输入推荐人');
        if(!$data['wechat_user_id']) return $this->fail('缺少参数');
        //验证码判断
        $smsRecordModel = new SmsRecord();
        $smsWhere = ['phone'=>$data['phone'],'type'=>'register'];
        $getInfo = $smsRecordModel->where($smsWhere)->order('sms_record_id','desc')->find();
        if(!$getInfo || (strtotime($getInfo['create_time']) + 30*60) < time() || $getInfo['is_use'] == 1){
            //return $this->fail('验证码已经过期');
        }
        //判断验证码是否正确
        if($getInfo['code'] != $data['sms_code']){
            //return $this->fail('验证码错误');
        }
        $userModel = new User();
        //获取用户
        $wechatUser = Db::name('wechat_user')->where('wechat_user_id',$data['wechat_user_id'])->find();
        if(!$wechatUser) return $this->fail('授权的用户不存在');
        if($wechatUser['user_id']){
            $bingUserInfo = $userModel->getUserInfoById($wechatUser['user_id'])->toArray();
        }else{
            $bingUserInfo = $userModel->bindWechatUser($data,$wechatUser);
        }
        if($bingUserInfo){
            $smsRecordModel->updateRecord($getInfo['sms_record_id'],['is_use'=>1]);
            $exp = intval(config('index.user_token_valid_exp', 15));
            $jwtTokenService = new IndexJwtService();
            $tokenInfo = $jwtTokenService->createToken($bingUserInfo,'user',strtotime("+ {$exp}day"));
            $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
            $saveData = [
                'last_time'=>date('Y-m-d H:i:s', time()),
                'last_ip'=>request()->ip(),
            ];
            $userResult = Db::table('jy_user')->where('id',$bingUserInfo['id'])->update($saveData);
            $backUser = [
                'user_id'=>$bingUserInfo['id'],
                'account'=>$bingUserInfo['account'],
                'real_name'=>$bingUserInfo['real_name'],
                'nickname'=>$bingUserInfo['nickname'],
                'phone'=>$bingUserInfo['phone'],
                'now_money'=>$bingUserInfo['now_money'],
            ];
            return $this->success('绑定成功',compact('backUser','tokenInfo'));
        }else{
            return $this->fail('绑定失败,请重试');
        }
    }

    /**
     * 获取微信授权信息
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     * @author xaboy
     * @day 2020-05-11
     */
    public function weChatAuth()
    {
        Log::info('进入授权');
        $backUrl = config('index.web_url')."/index/auth/wechat/back";
        $weChatService = new WeChatService();
        $oauth = $weChatService->init();
        $response = $oauth->oauth->scopes(['snsapi_userinfo'])
            ->redirect($backUrl);
        return $this->success('获取成功',['wechat_url'=>$response->getTargetUrl()]);

    }

    /**
     * 微信授权回调
     * @return $this
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function weChatAuthBack(){
        //dd(Request::get());
        $weChatService = new WeChatService();
        $oauth = $weChatService->init();
        $oauth  = $oauth->oauth;
        $user = $oauth->user();
        if(!$user) return $this->fail('微信授权登录失败');
        $openId = $user->getId();
        $weChatUserModel = new WechatUser();
        $weChatUser = $weChatUserModel->getInfoByOpenId($openId);
        //不存在微信用户
        if(!$weChatUser){
            $weChatUserId = $weChatUserModel->addWeChatUser($user,$openId,'wechat');
            if(!$weChatUserId) return $this->fail('授权登录失败');
            $weChatUser = $weChatUserModel->getInfoById($weChatUserId);
        }
        if(!$weChatUser) return $this->fail('微信授权登录失败,请重新授权');
        if(!$weChatUser['user_id'] || $weChatUser['user_id'] == 0){
            $backWechat = ['open_id'=>$openId,'wechat_user_id'=>$weChatUser['wechat_user_id']];
            return $this->success('请绑定手机号',$backWechat,0,-1);
        }
        $userModel = new User();
        $userInfo = $userModel->UserInfoById($weChatUser['user_id'])->toArray();
        //不存在用户
        if(!$userInfo){
            $saveData = ['user_id'=>0,'update_time'=>date("Y-m-d H:i:s")];
            $updateResult = $weChatUserModel->updateWeChatUser($weChatUser['wechat_user_id'],$saveData);
            if($updateResult){
                $backWechat = ['open_id'=>$openId,'wechat_user_id'=>$weChatUser['wechat_user_id']];
                return $this->success('请绑定手机号',$backWechat,0,-1);
            }else{
                return $this->fail('微信授权登录失败,请重新授权');
            }
        }
        //返回授权信息
        $exp = intval(config('index.user_token_valid_exp', 15));
        $jwtTokenService = new IndexJwtService();
        $tokenInfo = $jwtTokenService->createToken($userInfo,'user',strtotime("+ {$exp}day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
        ];
        $userResult = Db::table('jy_user')->where('id',$userInfo['id'])->update($saveData);
        $backUser = [
            'user_id'=>$userInfo['id'],
            'account'=>$userInfo['account'],
            'real_name'=>$userInfo['real_name'],
            'nickname'=>$userInfo['nickname'],
            'phone'=>$userInfo['phone'],
            'now_money'=>$userInfo['now_money'],
        ];
        return $this->success('获取成功',compact('backUser','tokenInfo'));

    }

    /**
     * 小程序授权登录
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    /*
    function appletAuth(){
        $getData = Request::post();
        if(!$getData['code']) return $this->fail('缺少code参数');
        if(!$getData['iv']) return $this->fail('缺少参数');
        if(!$getData['encryptedData']) return $this->fail('缺少参数');
        $appleService = new WeChatAppletService();
        $app = $appleService->init();
        $wechatUser = $app->auth->session($getData['code']);
        $decryptedData = $app->encryptor->decryptData($wechatUser['session_key'],$getData['iv'],$getData['encryptedData']);
        $openId = $wechatUser['openid'];
        $weChatUserModel = new WechatUser();
        $where = ['openid'=>$openId,'user_type'=>'applet'];
        $weChatUser = $weChatUserModel->getInfoByWhere($where);
        //不存在微信用户
        if(!$weChatUser){
            $weChatUserId = $weChatUserModel->addWeChatAppletUser($decryptedData,$openId,'applet');
            if(!$weChatUserId) return $this->fail('授权登录失败');
            $weChatUser = $weChatUserModel->getInfoById($weChatUserId);
        }
        if(!$weChatUser) return $this->fail('微信授权登录失败,请重新授权');
        $decryptedData['wechat_user_id'] = $weChatUser['wechat_user_id'];
        if(!$weChatUser['user_id'] || $weChatUser['user_id'] == 0){
            return $this->success('请绑定手机号',$decryptedData,0,-1);
        }
        $userModel = new User();
        $userInfo = $userModel->UserInfoById($weChatUser['user_id']);
        //不存在用户
        if(!$userInfo){
            $saveData = ['user_id'=>0,'update_time'=>date("Y-m-d H:i:s")];
            $updateResult = $weChatUserModel->updateWeChatUser($weChatUser['wechat_user_id'],$saveData);
            if($updateResult){
                return $this->success('请绑定手机号',$decryptedData,0,-1);
            }else{
                return $this->fail('微信授权登录失败,请重新授权');
            }
        }
        //返回授权信息
        $exp = intval(config('index.user_token_valid_exp', 15));
        $jwtTokenService = new IndexJwtService();
        $tokenInfo = $jwtTokenService->createToken($userInfo,'user',strtotime("+ {$exp}day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
        ];
        $userResult = Db::table('jy_user')->where('id',$userInfo['id'])->update($saveData);
        $backUser = [
            'user_id'=>$userInfo['id'],
            'account'=>$userInfo['account'],
            'real_name'=>$userInfo['real_name'],
            'nickname'=>$userInfo['nickname'],
            'phone'=>$userInfo['phone'],
            'now_money'=>$userInfo['now_money'],
        ];
        return $this->success('获取成功',compact('backUser','tokenInfo'));
    }
    */

    /**
     * 小程序授权登录
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    function appletAuth(){
        //$getData = request()->param(['code', 'iv','encryptedData']);
        $getData =  Request::post();
        if(!$getData['code']) return $this->fail('缺少code参数');
        if(!$getData['iv']) return $this->fail('缺少参数');
        if(!$getData['encryptedData']) return $this->fail('缺少参数');
        $appleService = new WeChatAppletService();
        $app = $appleService->init();
        $setData = $app->auth->session($getData['code']);
        if((isset($setData['errcode']) && $setData['errcode']) || !isset($setData['session_key'])) return $this->fail('获取授权内容错误',1,400,$setData);
        //dump($setData);
        $openId = $setData['openid'];
        //获取微信用户信息
        $weChatUserModel = new WechatUser();
        $where = ['routine_openid'=>$openId,'user_type'=>'applet'];
        $weChatUser = $weChatUserModel->getInfoByWhere($where);
        if(!$weChatUser){
            $decryptedData = $app->encryptor->decryptData($setData['session_key'],$getData['iv'],$getData['encryptedData']);
            //dump($decryptedData);
            Log::info('小程序授权数据'.json_encode($decryptedData,JSON_UNESCAPED_UNICODE));
            $weChatUserId = $weChatUserModel->addWeChatAppletUser($decryptedData,$openId,'applet');
            if(!$weChatUserId) return $this->fail('授权登录失败');
            $weChatUser = $weChatUserModel->getInfoById($weChatUserId);
        }
        if(!$weChatUser) return $this->fail('微信授权登录失败,请重新授权');
        $backPhoneData['wechat_user_id'] = $weChatUser['wechat_user_id'];
        $backPhoneData['openid'] = $openId;
        $backPhoneData['session_key'] = $setData['session_key'];
        if(!$weChatUser['user_id'] || $weChatUser['user_id'] == 0){
            return $this->success('请绑定手机号',$backPhoneData,0,-1);
        }
        $userModel = new User();
        $userInfo = $userModel->UserInfoById($weChatUser['user_id'])->toArray();
        //不存在用户
        if(!$userInfo){
            $saveData = ['user_id'=>0,'update_time'=>date("Y-m-d H:i:s")];
            $updateResult = $weChatUserModel->updateWeChatUser($weChatUser['wechat_user_id'],$saveData);
            if($updateResult){
                return $this->success('请绑定手机号',$backPhoneData,0,-1);
            }else{
                return $this->fail('微信授权登录失败,请重新授权');
            }
        }
        //返回授权信息
        $exp = intval(config('index.user_token_valid_exp', 15));
        $jwtTokenService = new IndexJwtService();
        $tokenInfo = $jwtTokenService->createToken($userInfo,'user',strtotime("+ {$exp}day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
        ];
        $userResult = Db::table('jy_user')->where('id',$userInfo['id'])->update($saveData);
        $backUser = [
            'user_id'=>$userInfo['id'],
            'account'=>$userInfo['account'],
            'real_name'=>$userInfo['real_name'],
            'nickname'=>$userInfo['nickname'],
            'phone'=>$userInfo['phone'],
            'now_money'=>$userInfo['now_money'],
        ];
        return $this->success('获取成功',compact('backUser','tokenInfo'));
    }

    /**
     * 小程序解密电话号码
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    function getApplePhone(){
        //$getData = request()->param(['code', 'iv','encryptedData','wechat_user_id','open_id']);
        $getData =  Request::post();
        if(!$getData['code']) return $this->fail('缺少code参数');
        if(!$getData['iv']) return $this->fail('缺少参数');
        if(!$getData['encryptedData']) return $this->fail('缺少参数');
        dump($getData);
        $appleService = new WeChatAppletService();
        $app = $appleService->init();
        $setData = $app->auth->session($getData['code']);
        if((isset($setData['errcode']) && $setData['errcode']) || !isset($setData['session_key'])) return $this->fail('获取授权内容错误',1,400,$setData);
        $decryptedData = $app->encryptor->decryptData($setData['session_key'],$getData['iv'],$getData['encryptedData']);
        if(isset($decryptedData['phoneNumber']) && $decryptedData['phoneNumber']){
            $backData = ['phone'=>$decryptedData['phoneNumber']];
            return $this->success('获取成功',$backData);
        }else{
            return $this->fail('获取手机号失败',1,400,$decryptedData);
        }
    }

    /**
     * 小程序绑定手机号
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
    */
    function appletBindPhone(){
        //$getData = request()->param(['code', 'iv','encryptedData','wechat_user_id','open_id']);
        $getData =  Request::post();
        //if(!$getData['code']) return $this->fail('缺少code参数');
        if(!$getData['iv']) return $this->fail('缺少参数');
        if(!$getData['encryptedData']) return $this->fail('缺少参数');
        if(!$getData['wechat_user_id']) return $this->fail('缺少微信用户信息');
        if(!$getData['open_id']) return $this->fail('缺少openId');
        if(!$getData['session_key']) return $this->fail('缺少参数');
        $weChatUserModel = new WechatUser();
        $where = ['wechat_user_id'=>$getData['wechat_user_id']];
        $weChatUser = $weChatUserModel->getInfoByWhere($where);
        if(!$weChatUser) return $this->fail('缺少微信用户信息,请重新授权');
        if($weChatUser['routine_openid'] != $getData['open_id']) return $this->fail('上传数据不一致');
        //未绑定用户信息
        if(!$weChatUser['user_id'] || $weChatUser['user_id'] == 0){
            $appleService = new WeChatAppletService();
            $app = $appleService->init();
            //$setData = $app->auth->session($getData['code']);
            $setData = ['session_key'=>$getData['session_key']];
            if((isset($setData['errcode']) && $setData['errcode']) || !isset($setData['session_key'])) return $this->fail('获取授权内容错误',1,400,$setData);
            $decryptedData = $app->encryptor->decryptData($setData['session_key'],$getData['iv'],$getData['encryptedData']);
            if(isset($decryptedData['purePhoneNumber']) && $decryptedData['purePhoneNumber']){
                $addData = ['phone'=>$decryptedData['purePhoneNumber']];
            }else if(isset($decryptedData['phoneNumber']) && $decryptedData['phoneNumber']){
                $addData = ['phone'=>$decryptedData['phoneNumber']];
            }else{
                return $this->fail('获取不到手机号',1,400,$decryptedData);
            }
            $weChatUser = $weChatUserModel->appletBindUser($weChatUser,$addData,'applet');
        }
        if(!$weChatUser['user_id']) return $this->fail('绑定手机号失败，请稍后重试');
        $userModel = new User();
        $userInfo = $userModel->UserInfoById($weChatUser['user_id'])->toArray();
        //不存在用户
        if(!$userInfo){
            $saveData = ['user_id'=>0,'update_time'=>date("Y-m-d H:i:s")];
            $updateResult = $weChatUserModel->updateWeChatUser($weChatUser['wechat_user_id'],$saveData);
            return $this->fail('绑定手机号失败，请稍后重试');
        }
        //返回授权信息
        $exp = intval(config('index.user_token_valid_exp', 15));
        $jwtTokenService = new IndexJwtService();
        $tokenInfo = $jwtTokenService->createToken($userInfo,'user',strtotime("+ {$exp}day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
        ];
        $userResult = Db::table('jy_user')->where('id',$userInfo['id'])->update($saveData);
        $backUser = [
            'user_id'=>$userInfo['id'],
            'account'=>$userInfo['account'],
            'real_name'=>$userInfo['real_name'],
            'nickname'=>$userInfo['nickname'],
            'phone'=>$userInfo['phone'],
            'now_money'=>$userInfo['now_money'],
        ];
        return $this->success('获取成功',compact('backUser','tokenInfo'));
    }


    /**
     * 小程序绑定手机号
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\DecryptException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException

    function appletBindPhone(){
        //$getData = request()->param(['code', 'iv','encryptedData','wechat_user_id','open_id']);
        $getData =  Request::post();
        if(!$getData['phone']) return $this->fail('缺少参数');
        if(!$getData['wechat_user_id']) return $this->fail('缺少微信用户信息');
        if(!$getData['open_id']) return $this->fail('缺少openId');
        $weChatUserModel = new WechatUser();
        $where = ['wechat_user_id'=>$getData['wechat_user_id']];
        $weChatUser = $weChatUserModel->getInfoByWhere($where);
        if(!$weChatUser) return $this->fail('缺少微信用户信息,请重新授权');
        if($weChatUser['routine_openid'] != $getData['open_id']) return $this->fail('上传数据不一致');
        //未绑定用户信息
        if(!$weChatUser['user_id'] || $weChatUser['user_id'] == 0){
            $weChatUser = $weChatUserModel->appletBindUser($weChatUser,$getData,'applet');
        }
        if(!$weChatUser['user_id']) return $this->fail('绑定手机号失败，请稍后重试');
        $userModel = new User();
        $userInfo = $userModel->UserInfoById($weChatUser['user_id'])->toArray();
        //不存在用户
        if(!$userInfo){
            $saveData = ['user_id'=>0,'update_time'=>date("Y-m-d H:i:s")];
            $updateResult = $weChatUserModel->updateWeChatUser($weChatUser['wechat_user_id'],$saveData);
            return $this->fail('绑定手机号失败，请稍后重试');
        }
        //返回授权信息
        $exp = intval(config('index.user_token_valid_exp', 15));
        $jwtTokenService = new IndexJwtService();
        $tokenInfo = $jwtTokenService->createToken($userInfo,'user',strtotime("+ {$exp}day"));
        $jwtTokenService->cacheToken($tokenInfo['token'], ($exp * 24 * 60 * 60));
        $saveData = [
            'last_time'=>date('Y-m-d H:i:s', time()),
            'last_ip'=>request()->ip(),
        ];
        $userResult = Db::table('jy_user')->where('id',$userInfo['id'])->update($saveData);
        $backUser = [
            'user_id'=>$userInfo['id'],
            'account'=>$userInfo['account'],
            'real_name'=>$userInfo['real_name'],
            'nickname'=>$userInfo['nickname'],
            'phone'=>$userInfo['phone'],
            'now_money'=>$userInfo['now_money'],
        ];
        return $this->success('获取成功',compact('backUser','tokenInfo'));
    }
     */
     
    /**
     * 获取微信有关配置
     * @return $this
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    function getWxConfig(){
        $getUrl = $this->request->param('web_url');
        $weChatService = new WeChatService();
        $app = $weChatService->init();
        $APIs = ['checkJsApi','miniProgram.navigateTo'];
        $getInfo = $app->jssdk->buildConfig( $APIs, $debug = false, $beta = false, $json = true,  $openTagList = [],$getUrl);
        $backInfo = json_decode($getInfo,true);
        return $this->success('获取成功',$backInfo);
    } 
}

